package org.anderground.editor.gui.menubar;

import static org.anderground.core.Logger.i;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;

import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.anderground.core.Logger;
import org.anderground.editor.gui.MainWindow;
import org.anderground.editor.model.EditorModel;
import org.anderground.editor.storage.ReadersRegistry;
import org.anderground.editor.storage.ReadersRegistry.FileFormat;
import org.anderground.modules.editor.importers.ModelImporter;


@SuppressWarnings("serial")
public class ImportMapMenu extends JMenu {
	public ImportMapMenu(final MainWindow parent) {
		super("Import map");
		for (final FileFormat format : ReadersRegistry.getFormats()) {
			// TODO add "getName" method to ImportReader
			JMenuItem item = new JMenuItem(format.getImporterClass()
					.getSimpleName());
			item.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent arg0) {
					if (MainWindow.modelChangedAfterLastSave)
						if (MainWindow
								.askForSave(
										"Do you want to open new file without saving current?",
										parent) != JOptionPane.CANCEL_OPTION)
							;
					showOpenFileDialog(parent, format);

					// should be called to centrate map
					parent.getMainPanel().getFirstView().afterPanelInit();
					parent.getMainPanel().getSecondView().afterPanelInit();

				}

			});
			this.add(item);
		}
	}

	public static void showOpenFileDialog(Component parent, FileFormat format) {
		JFileChooser fileCooser = new JFileChooser();
		FileFilter filter = new FileNameExtensionFilter(format
				.getFormatDescription(), format.getSupportedExtensions());
		fileCooser.addChoosableFileFilter(filter);

		if (fileCooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
			File f = fileCooser.getSelectedFile();
			i("selected file: " + f.getName());
			try {
				ModelImporter importer = format.getImporterClass()
						.newInstance();
				EditorModel.getInstance().load(importer.read(f));
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				Logger.w("file " + f.getName() + "not found");
			}
			// EditorModel.getInstance().load(f.getAbsolutePath());
			MainWindow.modelChangedAfterLastSave = false;
		}

	}
}
